//
// Created by yyl on 2018/6/5.
//

#include "../yyl_log.h"
#include "queue"
#include "unistd.h"
#include "OnCallBack.h"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
//生产者线程
pthread_t producPid;
//消费者线程
pthread_t customPid;

pthread_mutex_t mutex;//锁
pthread_cond_t cond;

std::queue<int> queue;

bool exitPthread = false;
OnCallBack *callBackJava;

void *producCallBack(void *data) {//生产者线程
    int count = 10;
    while (!exitPthread) {
        pthread_mutex_lock(&mutex);//加锁
        ++count;
        queue.push(count);
        LOGI("生产一个产品%d", count);
        pthread_cond_signal(&cond);//通知cond不用等待
        usleep(1000 * 500);//0.5秒钟
        pthread_mutex_unlock(&mutex);//解锁

        if (count > 14) {
            pthread_cond_signal(&cond);//通知cond不用等待
            exitPthread = true;
        } else {
            sleep(3);//5秒钟
        }
    }
    LOGI("exit生产   producPid");
    callBackJava->onCallBackPrint(0, "Stop  producPid");
    pthread_exit(&producPid);
}

void *customCallBack(void *data) {//消费者线程
    while (!exitPthread) {
        pthread_mutex_lock(&mutex);//加锁
        if (!queue.empty()) {
            const int numb = queue.front();
            queue.pop();
            LOGI("消费一个产品%d", numb);
        } else {
            LOGI("没有产品消费等待中...");
            pthread_cond_wait(&cond, &mutex); //阻塞
        }
        pthread_mutex_unlock(&mutex);//解锁

    }
    LOGI("exit消费   customPid");
    callBackJava->onCallBackPrint(0, "Stop  customPid");
    pthread_exit(&customPid);
}


void testThread() {
    for (int i = 0; i < 10; ++i) {
        queue.push(i);
    }
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_create(&producPid, NULL, producCallBack, NULL);
    pthread_create(&customPid, NULL, customCallBack, NULL);

}


extern "C"
JNIEXPORT void JNICALL
Java_com_yyl_jni_MyVideo_testPthread(JNIEnv *env, jobject instance) {
    callBackJava = new OnCallBack(env, env->NewGlobalRef(instance));
    callBackJava->onCallBackPrint(1, "Start");
    testThread();

}

//JNIEXPORT jint JNICALL
//JNI_OnLoad(JavaVM *vm, void *reserved) {
//    JNIEnv *jniEnv;
//    if (vm->GetEnv((void **) &jniEnv, JNI_VERSION_1_6) != JNI_OK) {
//        return -1;
//    }
//    LOGI("JNI_VERSION_1_6");
//    return JNI_VERSION_1_6;
//}


#pragma clang diagnostic pop